package com.atguigu.gulimail.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class GulimailCorsConfiguration {

    @Bean
    //1、需要返回一个CorsWebFilter过滤器
    public CorsWebFilter getCorsWebFilter() {
        //2、因为CorsWebFilter()的构造器需要CorsConfigurationSource,（CorsConfigurationSource是接口），所以创建
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        //3、要想实现跨域，就要调用CorsConfigurationSource的registerCorsConfiguration方法
        //CorsConfigurationSource没有registerCorsConfiguration方法。
        //4、创建CorsConfiguration类，配置规则
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(corsConfigurationSource);
    }

}
